package com.qf.util;

import com.qf.bean.Employee;
import com.qf.bean.Menu;
import com.qf.bean.Role;
import com.qf.dao.EmployeeMapper;
import com.qf.dao.MenuMapper;
import com.qf.dao.RoleMapper;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.List;

/**
 * 2019/11/26
 * 键盘敲烂，月薪过万
 * 登高必自卑，行远必自迩。
 * 不忘初心：像初学者一样拥有一颗谦虚、开放的心态。
 * 李学峰
 */
public class MyRealm extends AuthorizingRealm {
    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private MenuMapper menuMapper;


    @Override//授权
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("授权开始");
        //1得到认证通过后的角色
        Employee epm = (Employee)principalCollection.getPrimaryPrincipal();
        //2权限 角色+url
        //2.1根据用户名查询角色
        Role role = roleMapper.selectByPrimaryKey(epm.getRoleid());
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.addRole(role.getRname());
        //2.2请求权限
        List<Menu> permission= menuMapper.findPermissionByRoleId(role.getRoleid());
        ArrayList permissionlist = new ArrayList<>();
        for (Menu menu : permission) {
            permissionlist.add(menu.getPercode());
        }
        info.addStringPermissions(permissionlist);


        return info;
    }

    @Override//认证
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("认证开始");
       //1.得到用户提交的用户名和密码
        String username =(String) authenticationToken.getPrincipal();
        //2传给数据库进行查询
        Employee employee = employeeMapper.login(username);
        //3判断用户是否正确
            if (employee==null){
                System.out.println("认证结束1");
                return null;
            }else {
                //参数正确的用户名，密码，盐值，自定义名称
                System.out.println("认证结束2");
                return new SimpleAuthenticationInfo(employee,employee.getLoginpassword(), ByteSource.Util.bytes(employee.getSalt()),"myreale");
            }
    }
}
